define(function(require, exports){
	var $ = require('jquery');
	var pubjs = require('pubjs');
	var util  = require('util');
	var view  = require('@base/view');
	var pop  = require('@layout/v1/popbar');
	var drop = require('@base/common/drop');
	var popwin = require('@base/dialog');
	var date = require('@base/common/date');

	// 子表格业务Crumb
	var Crumb = pop.crumb.extend({
		init: function(config){
			config = pubjs.conf(config, {

			});

			this.Super('init', arguments);
		},
		// 构建层级
		buildLevel: function(level, config){
			var self = this;
			var doms = self.$doms;
			var c = self.getConfig();

			if(!self.$level[level]){

				var data = self.$level[level] = {};
				var levelCon = data['levelCon'] = doms.con.find('div[data-con="'+level+'"]');

				// 灰色左边
				if(!data['left']){
					data['left'] = self.create('level_left_'+level, drop.drop, {
						'addClass': 'gray',
						'target': levelCon.find('.dropCon'),
						'hasSearch': false,
						'width': 80,
						'height': 40,
						'hasTitle': true,
						'hasEvent': false,
						'panel_config': {
							'hasArrow': true,
							'appendTo': 'popup'
						}
					});
				}

				// 白色右边
				if(!data['right']){
					data['right'] = self.create('level_right_'+level, drop.drop, {
						'addClass': 'pure level_right',
						'target': levelCon.find('.dropCon'),
						'width': 170,
						'height': 40,
						'name': 'Name',
						'key': '_id',
						'result_line_height': '15px',
						'result_render': self.renderResult,
						'hasEvent': false,
						'all': {'Name': LANG('全部'), '_id': -10000},
						'panel_config': {
							'appendTo': 'popup',
							'hasSearch': false,
							'hasArrow': true,
							'width': 310,
							'height': 300,
							'option_height': 50,
							'option_line_height': 18,
							'option_render': self.renderOption,
							'option_class': 'spacing',
							'toolbar': {
								'modName': 'toolbar',
								'uri': 'modules/crumb.campaignCustomTool',
								'config': {}
							}
						}
					});
				}

				// 白色右边时段分析
				if(!data['rightPeriod']){
					data['rightPeriod'] = self.create('level_rightPeriod_'+level, drop.drop, {
						'addClass': 'pure level_rightPeriod dn',
						'target': levelCon.find('.dropCon'),
						'hasSearch': false,
						'options': c.periodOptions,
						'all': {'name': LANG('全部'), 'id': -10000},
						'width': 60,
						'height': 40,
						'hasEvent': false,
						'panel_config': {
							'hasArrow': true,
							'appendTo': 'popup',
							'toolbar': {
								'modName': 'toolbar',
								'uri': 'modules/crumb.periodCustomTool',
								'config': {}
							}
						}
					});
				}

				// 前置箭头
				if(!data['arrow']){
					data['arrow'] = $([
						'<div class="levelArrow">',
							'<span/>',
							'<i class="triangle-left"/>',
						'</div>'
					].join('')).appendTo(levelCon.find('>.arrowCon'));
				}

				// 删除按钮
				if(!data['cancel']){
					data['cancel'] = $([
						'<div class="levelCancel">',
							'<i class="icon-close"/>',
						'</div>'
					].join('')).appendTo(levelCon.find('.cancelCon'));

					self.uiBind(levelCon.find('.cancelCon'), 'mouseover mouseout', 'eventCancelMouse');
				}

			}

			return self;
		},
		// 更新层级
		updateLevel: function(config, isSubSource){
			if(!config){
				return;
			}
			var self = this;
			var c = self.getConfig();
			var level; // 层级
			var levelModule; // 层级包含的所有组件

			// 根据condition参数判断是什么层级，然后设置不同的层级的drop
			if(config.condition){
				level = self.$currentLevel = config.condition.length;
			}else{
				level = self.$currentLevel + 1;
			}

			levelModule = self.$level[level];

			if(levelModule){
				var levelCon = levelModule['levelCon'];
				var left = levelModule['left'];
				var right = levelModule['right'];
				var rightPeriod = levelModule['rightPeriod'];
				var options;

				if(config && left && right && rightPeriod){
					if(level > 1){
						options = config.subOptions || [];
					}else{
						options = c.baseOptions;
					}

					// 记录数据到levelData;
					self.$levelData.push(config);

					// 是subSource的时候，绑定删除层级x事件
					if(isSubSource){
						// 先移除
						self.uiUnbind(levelModule['cancel'], 'click', 'eventCancelLevel');
						// 再绑定
						self.uiBind(levelModule['cancel'], 'click', config, 'eventCancelLevel');
					}


					// 设置新的options，清除标记
					left.setData(options).setFlag('').removeClass('blue');


					if(isSubSource){
						left.setFlag('end'); // 是subSource时设置结束标记，给标题使用
					}

					// 设值，入口层通常没有subName，所以用gridName，二级后都需要默认配置有subName
					left.setValue(config.subName || config.gridName || '');

					// 更新key
					right.getPanel().setConfig('key', config.key || '_id');
					// 更新nameKey
					if(config.nameKey){
						right.getPanel().setConfig('name', config.nameKey);
					}else{
						right.getPanel().setConfig('name', 'Name');
					}

					// 这里要根据表格处理right的options，如时段分析比较特殊；
					if(config.subName == 'period' || config.subName == 'frequency' || config.subName == 'amount_period' || config.subName == 'compare_period'){

						rightPeriod.setFlag(config.subName).setValue('hour').removeClass('dn');
						right.addClass('dn');
					}else{

						// 客户列表不能通过ids查询，所以还是查找全部
						var ids = {'ids':String(config.id)};
						if(config.gridName == 'user'){
							ids = {};
						}

						if(!isSubSource){

							if(config.popType == 'compare'){
								// 对比报表处理
								if(level < 2){
									right.setData(self.getSelectsData(config, config.key), 'noAll');
								}
								right.setDef(config.selects.length + LANG('个'));
								right.toggleToolbar(true).toggleEvent(true);
								// 暂时不让后边的可点击
								if(level > 1){
									right.toggleToolbar(false).toggleEvent(false);
								}
							}else{
								// 组合维度处理
								right.setData(config.gridData);
								right.setDef('', true);
							}
						}

						rightPeriod.addClass('dn');
						right.reset()
							.setParam(util.extend(config.param, ids))
							.setConfig('url', config.url)
							.setConfig('value', config.id || -10000)
							// .load()
							.setFlag(config.subName)
							.setValue(config.id)
							.removeClass('dn');

						if(!isSubSource){
							if(config.name == LANG('汇总')){
								right.setValue(-10000);
							}
						}
					}


					// 显示和隐藏levelCon
					levelCon.show().nextAll().hide();

					if(isSubSource){

						right.setDef('', true);
						if(config.popType != 'compare'){
							// right.setData([]);
							rightPeriod.disableItem(-10000);
						}
						// 最后一级，暂时设置全部
						right.setValue(-10000);
						rightPeriod.setValue(-10000);
						right.toggleToolbar(false);
						right.toggleEvent(false);

						// 最后一个删除按钮变颜色, 前面的移除颜色;
						levelCon.find('>.cancelCon').addClass('cancelEnd').show();
						levelCon.prev().find('>.cancelCon').removeClass('cancelEnd');

					}else{

					}
				}
			}

			// 如果有subSource，继续执行一次
			if(config.subSource){
				self.updateLevel(config.subSource, 'isSubSource');
			}

			return self;
		},
		onDropChange: function(ev){
			this.Super('onDropChange', arguments);

			if(ev.name.indexOf('level_rightPeriod') != -1){
				if(ev.param && !ev.param.isTrigger){
					// console.log(ev.param.option.value);
				}
			}

		},
		onComparePeriodChangeTime: function(ev){
			var self = this;
			var level = self.$level;
			var currentRightPeriod;
			// 查找最后一个时段分析
			util.each(level, function(item, idx){
				if(item){
					if(item.levelCon.is(':visible')){
						if(item.rightPeriod.getDOM().is(':visible')){
							currentRightPeriod = item.rightPeriod;
						}
					}
				}
			});

			if(currentRightPeriod){
				currentRightPeriod.setValue(ev.param);
			}
			return false;
		},
		onCampaignSelect: function(ev){
			var data = ev.param;
			var ids = [];
			var condition;
			util.each(data.items, function(item){
				if(item && item._id){
					ids.push(item._id);
				}
			});
			if(data){
				// 更新drop数据
				data.drop.setData(data.items, 'noAll');
				data.drop.setDef(data.items.length + LANG('个'));
			}
			var mod = this.getSubGridMod();
			if(mod){
				var param = mod.getConfig('param');
				condition = JSON.parse(param.condition);
				util.each(condition, function(item){
					if(item && item.hasOwnProperty('campaign_id')){
						item.campaign_id = ids;
						return;
					}
				});
			}
			condition = JSON.stringify(condition);
			mod.setParam({'condition': condition}).load();
			return false;
		},
		onPeriodDateSelect: function(ev){
			if(ev && ev.param){
				var date = ev.param.items;
				var mod = this.getSubGridMod();
				if(mod){
					var param = mod.getConfig('param');
					date.unshift({
						'begindate': param.begindate,
						'enddate': param.enddate
					});
				}
				mod.load({'date': JSON.stringify(date)});
			}
		}
	});
	exports.crumb = Crumb;


	// 复制pubjs的pop的对外方法
	for(var i in pop){
		if(i != 'crumb'){
			exports[i] = pop[i];
		}
	}

	// 活动-自定义drop组件
	var CampaignCustomTool = view.container.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				'class': 'M-crumbCampaignCustomTool'
			});
			this.Super('init', arguments);
		},
		afterBuild: function() {
			var self = this;
			// var c = self.getConfig();
			var el = self.getDOM();

			el.append($([
				'<div class="dateCon"/>',
					'<span class="add link">'+LANG('编辑')+'</span>',
				'</div>'
			].join('')));

			self.uiBind(el.find('.add'), 'click', 'eventClick');
		},
		eventClick: function(evt, elm){
			var self = this;
			var pop = self.get('campaignPop');
			if(!pop){
				pop = self.create('campaignPop', CampaignPop);
			}
			pop.show();
			self.parent().hide();
			return false;
		}
	});
	exports.campaignCustomTool = CampaignCustomTool;

	// 活动-选择活动弹层
	var CampaignPop = popwin.base.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				'title': LANG('选择活动'),
				'size': 'xl'
			});

			this.Super('init', arguments);
		},
		afterBuild: function() {
			var self = this;
			self.Super('afterBuild', arguments);
			// var c = self.getConfig();
			var el = self.getDOM('body');

			el.append($([
				'<div class="cl mt20" pub-name="highGrid" pub-mod="campaign/grid/campaign.base"/>'
			].join('')));

			self.buildFromTemplate({
				'highGrid': {
					hasMenu: false,
					hasSwitch: false,
					hasBatch: false,
					hasSelect: true,
					hasAmount: false,
					hasAutoRefresh: false,
					eventDataLoad: true, // 加载完数据后发消息
					hasExport: false,
					hasRefresh: true,
					hasTab: true,
					hasSearch: true,
					hasFilter: false,
					hasSubGrid: false,
					pager: {
						size: 10
					},
					param: {}
				}
			});
		},
		afterBuildTemplate: function(mod, param){
			var self = this;
			var gird = self.get('highGrid');
			if(gird){
				var con = gird.getDOM().find('.M-HighGridHeaderLeft');
				$([
					'<div class="dib valign-m lh30 ml20">',
						'<label class="mr10 cur_p">',
							'<input type="checkbox" class="mr5"/>',
							LANG('显示已选'),
							'<span/>',
						'</label>',
						'<span class="tips font-danger fs12">',
							LANG('不可超过5个选项'),
						'</span>',
					'</div>'
				].join('')).appendTo(con);
				con.find('input').css('vertical-align', '-2px');

				self.uiBind(con.find('input'), 'click', 'eventSelected');
			}
		},
		eventSelected: function(evt, elm){
			var val = $(elm).prop('checked');
			var highGrid = this.$.highGrid;
			var ids = highGrid.getSelectRowIds();
			highGrid.setParam({
				'ids': val ? ids : null
			});
			highGrid.load();
		},
		onOk: function() {
			var self = this;

			var ids = self.$.highGrid.getSelectRowIds();
			var data = {
				'items': self.$.highGrid.getData(ids),
				'drop': self.parent().parent().parent()
			}

			if(ids.length > 5){
				pubjs.alert(LANG('不可超过5个选项'));
				return false;
			}
			self.hide();
			self.fire('campaignSelect', data);
			return false;
		},
		reset: function() {
			var self = this;

			return self;
		}
	});
	exports.campaignPop = CampaignPop;

	// 时段分析-自定义drop组件
	var PeriodCustomTool = view.container.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				'class': 'M-crumbPeriodCustomTool'
			});
			this.Super('init', arguments);
		},
		afterBuild: function() {
			var self = this;
			// var c = self.getConfig();
			var el = self.getDOM();

			el.append($([
				'<div class="dateCon"/>',
					'<span class="add">'+LANG('自定义')+'</span>',
				'</div>'
			].join('')));

			self.uiBind(el.find('.add'), 'click', 'eventClick');
		},
		eventClick: function(evt, elm){
			var self = this;
			var pop = self.get('periodDatePop');
			if(!pop){
				pop = self.create('periodDatePop', PeriodDatePop);
			}
			pop.show();
			self.parent().hide();
			return false;
		}
	});
	exports.periodCustomTool = PeriodCustomTool;

	// 时段分析-时间弹层
	var PeriodDatePop = popwin.base.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				'title': LANG('添加时间'),
				'size': 'm',
				'max': 2,
				'hasFocusFirstInput': false
			});

			this.$dateData = [];
			this.$index = 0;

			this.Super('init', arguments);
		},
		afterBuild: function() {
			var self = this;
			self.Super('afterBuild', arguments);
			// var c = self.getConfig();
			var el = self.getDOM('body');

			el.append($([
				'<div class="dateCon"/>',
				'<span class="link addDate mt20 dib">'+LANG('添加')+'</span>'
			].join('')));

			self.uiBind(el.find('>.addDate'), 'click', 'eventAddDate');
			self.uiProxy(el, '.closeDate', 'click', 'eventCloseDate');
		},
		buildDate: function(){
			var self = this;
			var c = self.getConfig();
			var con = self.getDOM('body').find('.dateCon');
			var index = self.$index++;

			if(self.$dateData.length >= c.max){
				pubjs.notify(LANG('暂时只支持添加2个时间段'), '', 'danger');
				return;
			}

			var item = $([
				'<div class="dateItem mt20">',
					'<div class="item dib"></div>',
					'<i class="valign-m icon-close font-warning ml10 cur_p closeDate"/>',
				'</div>'
			].join('')).appendTo(con);

			var dateRangeNew = self.create('date_'+index, date.dateRangeNew, {
				'broadcast': false,
				'showButton': false,
				'userStorage': false,
				'target': item.find('.item')
			});

			self.$dateData.push({
				'index': index,
				'con': item,
				'date': dateRangeNew,
				'close': item.find('>.closeDate').attr('data-index', index)
			});



			return self;
		},
		eventAddDate: function(evt, elm){
			var self = this;
			self.buildDate();
			return false;
		},
		eventCloseDate: function(evt, elm){
			var self = this;
			var index = $(elm).attr('data-index');
			self.removeDateItem(index);
			return false;
		},
		onOk: function() {
			var self = this;
			var date = [];

			util.each(self.$dateData, function(item){
				if(item && item.date){
					var date_tmp = item.date.getData('isTimeStamp', true);
					date.push({
						'begindate': date_tmp.begin,
						'enddate': date_tmp.end
					});
				}
			});

			var data = {
				'items': date,
				'drop': self.parent().parent().parent()
			};

			self.hide();
			self.fire('periodDateSelect', data);
			return false;
		},
		removeDateItem: function(index){
			var self = this;
			var dateItem = util.find(self.$dateData, index, 'index');
			if(dateItem){
				dateItem.date.destroy();
				dateItem.con.remove();
				util.remove(self.$dateData, index, 'index');
			}
		},
		reset: function() {
			var self = this;
			var dateData = self.$dateData;
			var i = 0;

			while (i <= dateData.length){
				if(!dateData.length){
					break;
				}
				self.removeDateItem(dateData[i].index);
			}

			self.$index = 0;
			return self;
		}
	});
	exports.periodDatePop = PeriodDatePop;

});